package flyshoes.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import flyshoes.mybatis.entity.Order;
import flyshoes.mybatis.entity.Product;
import flyshoes.mybatis.entity.Result;
import flyshoes.mybatis.entity.ShoppingCart;
import flyshoes.mybatis.enums.OrderStatus;
import flyshoes.mybatis.mapper.OrderMapper;
import flyshoes.mybatis.service.serviceImpl.OrderServiceImpl;
import flyshoes.mybatis.service.serviceImpl.ProductServiceImpl;
import flyshoes.mybatis.service.serviceImpl.ShoppingcartServiceImpl;
import flyshoes.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class MyOrderServiceImpl {
    private final OrderServiceImpl orderService;
    //private final RabbitTemplate rabbitTemplate;
    private final ProductServiceImpl productService;
    private final ShoppingcartServiceImpl cartService;
    @Transactional
    public Result allOrder(){ //查找所有的订单
        Integer userId = ThreadLocalUtil.get();
        List<Order> list = orderService.lambdaQuery().eq(Order::getUserId,userId).list();
        if (list.isEmpty()){
            return Result.fail(400,"暂无商品");
        }

        return Result.success(list);
    }
    @Transactional
    public Result notPayOrder(){            //查找未支付的订单
        Integer userId = ThreadLocalUtil.get();
        List<Order> list = orderService.lambdaQuery().eq(Order::getUserId,userId)
                .eq(Order::getOrderStatus,OrderStatus.NOTPAY)
                .list();
        if (list.isEmpty()){
            return Result.fail(400,"暂无商品");
        }

        return Result.success(list);
    }
    @Transactional
    public Result alreadyPayOrder(){        //查找已支付的订单
        Integer userId = ThreadLocalUtil.get();
        List<Order> list = orderService.lambdaQuery().eq(Order::getUserId,userId)
                .eq(Order::getOrderStatus,OrderStatus.ALREADYPAY)
                .list();
        if (list.isEmpty()){
            return Result.fail(400,"暂无商品");
        }
        return Result.success(list);
    }
    @Transactional
    public Result createdOrder(List<Order> order) {           //生成单个或多个商品的订单
        Integer userId = ThreadLocalUtil.get();
        String orderNumber = "FS" + UUID.randomUUID();
        //List<Integer> list = new ArrayList<>();
//        for (Order order1 : order) {
//            list.add(order1.getProductId());
//        }
        for (Order orderDB : order) {
            orderDB.setUserId(userId);
            orderDB.setOrderStatus(OrderStatus.NOTPAY); //待支付
            orderDB.setOrderNumber(orderNumber);
            orderDB.setCreatedTime(LocalDateTime.now());
            Product product = productService.lambdaQuery().eq(Product::getId, orderDB.getProductId()).one();
            Product productDb = productService.lambdaQuery().eq(Product::getId, orderDB.getProductId()).one();
            product.setStockQuantity(productDb.getStockQuantity()- orderDB.getItemCount());
            orderDB.setItemPrice(orderDB.getItemCount() * product.getPrice());
            //如果商品在购物车里，则删除
            boolean c = cartService.lambdaQuery().eq(ShoppingCart::getProductId, orderDB.getProductId())
                    .eq(ShoppingCart::getUserId,userId)
                    .exists();
            if (c){
                QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<ShoppingCart>().eq("user_id",userId)
                                .eq("product_id",orderDB.getProductId());
                cartService.remove(queryWrapper);
            }else {
                System.out.println("商品不在购物车");
            }
            boolean b = orderService.save(orderDB);
            if (!b) {
                return Result.fail("创建订单失败");
            }
        }
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("SUM(item_price) AS totalPrice","SUM(item_count) AS totalAmount")
                .eq("order_number", orderNumber);
        Map<String, Object> map = this.orderService.getMap(queryWrapper);
        BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");
        BigDecimal totalAmount = (BigDecimal) map.get("totalAmount");
        orderService.lambdaUpdate().eq(Order::getOrderNumber, orderNumber)
                .set(Order::getTotalPrice, totalPrice)
                .set(Order::getTotalAmount,totalAmount)
                .update();


        //rabbitTemplate.convertAndSend("order.direct", "order.create.success", list);
        return Result.success(orderNumber);
    }
    @Transactional
    public Result deleteOrder(Integer productId){//删除订单
        Integer userId = ThreadLocalUtil.get();
        Order orderDb = orderService.lambdaQuery().eq(Order::getProductId,productId)
                .eq(Order::getUserId,userId)
                .one();
        boolean b = orderService.removeById(orderDb);
        if (!b){
            return Result.fail("失败");
        }
        return Result.success("成功");
    }


}
